package org.example.ratelimit2;

import org.example.ratelimit2.impl.TokenBucketRateLimiter;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class LimiterTest {
    public static void main(String[] args) {
        // 1分钟100个请求，6个窗口加起来100个
        // 10秒内只允许100个请求
        // MyRateLimiter limiter = new SlidingWindowRateLimiter2(100, 1, 10);
        // 每秒只放行2个，容量为10
        MyRateLimiter limiter = new TokenBucketRateLimiter(10, 2);
        for (;;) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            AtomicInteger success = new AtomicInteger(0);
            AtomicInteger fail = new AtomicInteger(0);

            Random random = new Random();
            int i = random.nextInt(3);
            long start = System.currentTimeMillis();
            i = 1;
            if (i == 1) {
                for (int j = 0; j < 100; j++) {
                    if (limiter.tryAcquire()) {
                        success.incrementAndGet();
                    } else {
                        fail.incrementAndGet();
                    }
                }
            } else if (i == 2) { // 模拟1秒内请求9次
                for (int j = 0; j < 200; j++) {
                    if (limiter.tryAcquire()) {
                        success.incrementAndGet();
                    } else {
                        fail.incrementAndGet();
                    }
                }
            } else { // 模拟1秒内请求10次
                for (int j = 0; j < 300; j++) {
                    if (limiter.tryAcquire()) {
                        success.incrementAndGet();
                    } else {
                        fail.incrementAndGet();
                    }
                }
            }
            int total = success.get() + fail.get();
            System.out.println("1秒内没有限流：" + success.get() + ", 限流：" + fail.get() + ", 总的请求数：" + total + ", 耗时：" + (System.currentTimeMillis() - start)/1000);
        }
    }
}
